﻿/*******************************************************************************
Copyright (c) 2011-2013, PKStudio
Copyright (c) 2011,      Zynga Inc.
Copyright (c) 2008-2010, Ricardo Quesada

http://pkstudio.org

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

Use any of these editors to generate BMFonts:
	http://www.angelcode.com/products/bmfont/ (Free, Windows only)
	http://www.n4te.com/hiero/hiero.jnlp (Free, Java)
	http://slick.cokeandcode.com/demos/hiero.jnlp (Free, Java)
*******************************************************************************/

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;

namespace PKEngine
{
	/// <summary>
	/// BmpFont definition.
	/// </summary>
	public class PKBmpFontDef
	{
		/// <summary>
		/// ID of the character.
		/// </summary>
		public ushort CharId { get; set; }

		/// <summary>
		/// Origin and size of the font.
		/// </summary>
		public Rectangle Rect { get; set; }

		/// <summary>
		/// The X amount the image should be offset when drawing the image.
		/// </summary>
		public int XOffset { get; set; }

		/// <summary>
		/// The Y amount the image should be offset when drawing the image.
		/// </summary>
		public int YOffset { get; set; }

		/// <summary>
		/// The amount to move the current position after drawing the character.
		/// </summary>
		public int XAdvance { get; set; }
	}

	/// <summary>
	/// BmpFont padding.
	/// </summary>
	public class PKBmpFontPadding
	{
		/// <summary>
		/// Padding left.
		/// </summary>
		public int Left { get; set; }

		/// <summary>
		/// Padding top.
		/// </summary>
		public int Top { get; set; }

		/// <summary>
		/// Padding right.
		/// </summary>
		public int Right { get; set; }

		/// <summary>
		/// Padding bottom.
		/// </summary>
		public int Bottom { get; set; }
	}

	/// <summary>
	/// PKBmpFontConfig has parsed configuration of the the .fnt file.
	/// </summary>
	public class PKBmpFontConfig
	{
		#region Private Fields
		private Dictionary<uint, int> kerningDict; // Key: 16-bit for 1st item, 16-bit for 2nd item.
		#endregion

		#region Public Properties
		public Dictionary<ushort, PKBmpFontDef> FontDefDict { get; private set; }
		public List<char> CharacterList { get; private set; }
		public string Name { get; private set; }
		public int CommonHeight { get; private set; }
		public PKBmpFontPadding Padding { get; private set; }
		#endregion

		#region Initialization
		public PKBmpFontConfig(string fntFile)
		{
			Debug.Assert(!string.IsNullOrEmpty(fntFile), "PKBmpFontConfig: Argument cannot be null.");
			Debug.Assert(File.Exists(fntFile), "PKBmpFontConfig: Cannot find file.");

			this.kerningDict = new Dictionary<uint, int>();
			this.FontDefDict = new Dictionary<ushort, PKBmpFontDef>();
			this.CharacterList = this.ParseConfigFile(fntFile);
		}
		#endregion

		#region Public Methods
		/// <summary>
		/// Get the kerning amount.
		/// </summary>
		/// <param name="first">first character</param>
		/// <param name="second">second character</param>
		/// <returns>Kerning amount</returns>
		public int GetKerningAmount(ushort first, ushort second)
		{
			int result = 0;

			unchecked
			{
				uint key = (uint)((first << 16) | (second & 0xffff));
				if (kerningDict != null && kerningDict.ContainsKey(key))
				{
					result = kerningDict[key];
				}
			}

			return result;
		}

		/// <summary>
		/// Get the width of a string.
		/// </summary>
		/// <param name="text">Specified string</param>
		/// <param name="spacing">Spacing</param>
		/// <returns>Width of string</returns>
		public int MeasureString(string text, int spacing)
		{
			int stringWidth = 0;

			ushort prev = 0xffff;
			ushort current;
			foreach (char ch in text)
			{
				if (ch == '\n')
				{
					break;
				}

				current = (ushort)ch;
				if (FontDefDict.ContainsKey(current))
				{
					stringWidth += FontDefDict[current].XAdvance + this.GetKerningAmount(prev, (ushort)ch) + spacing;
				}
				prev = current;
			}
			if (stringWidth > 0)
			{
				stringWidth -= spacing;
			}

			return stringWidth;
		}
		#endregion

		#region Private Methods
		private List<char> ParseConfigFile(string fntFile)
		{
			string contents = string.Empty;
			using (StreamReader reader = new StreamReader(fntFile, Encoding.UTF8))
			{
				contents = reader.ReadToEnd().Replace("\r", "");
			}
			Debug.Assert(!string.IsNullOrEmpty(contents), "PKBmpFontConfig.ParseConfigFile: Error parsing FNT file.");

			List<char> validCharsList = new List<char>();

			// Move all lines in the string, which are denoted by \n, into an array.
			string[] lines = contents.Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);

			// Loop through all the lines in the lines array processing each one.
			foreach (string line in lines)
			{
				if (line.StartsWith("info face"))
				{
					this.ParseInfoArguments(line);
				}
				else if (line.StartsWith("common lineHeight"))
				{
					this.ParseCommonArguments(line);
				}
				else if (line.StartsWith("page id"))
				{
					this.ParseImageFileName(line, fntFile);
				}
				else if (line.StartsWith("chars c"))
				{
					// Ignore.
				}
				else if (line.StartsWith("char"))
				{
					// Parse the current line and create a new CharDef.
					PKBmpFontDef fontDef = PKBmpFontConfig.ParseCharDef(line);
					this.FontDefDict.Add(fontDef.CharId, fontDef);
					validCharsList.Add((char)fontDef.CharId);
				}
				else if (line.StartsWith("kerning first"))
				{
					this.ParseKerningEntry(line);
				}
			}

			return validCharsList;
		}

		private void ParseInfoArguments(string line)
		{
			// For example:
			// info face="Script" size=32 bold=0 italic=0 charset="" unicode=1 stretchH=100 smooth=1 aa=1 padding=1,4,3,2 spacing=0,0 outline=0
			// info face="微软雅黑 Bold" size=24 bold=1 italic=0 charset="" unicode=0 stretchH=100 smooth=1 aa=1 padding=0,0,0,0 spacing=1,1
			Match match = Regex.Match(line, @"padding=(?<top>\d+),(?<right>\d+),(?<bottom>\d+),(?<left>\d+) ");
			Debug.Assert(match.Success, "PKBmpFontConfig.ParseInfoArguments: Cannot get correct arguments.");

			this.Padding = new PKBmpFontPadding();
			this.Padding.Left = int.Parse(match.Groups["left"].Value);
			this.Padding.Right = int.Parse(match.Groups["right"].Value);
			this.Padding.Top = int.Parse(match.Groups["top"].Value);
			this.Padding.Bottom = int.Parse(match.Groups["bottom"].Value);
		}

		private void ParseCommonArguments(string line)
		{
			// For example:
			// common lineHeight=104 base=26 scaleW=1024 scaleH=512 pages=1 packed=0
			// common lineHeight=33 base=26 scaleW=256 scaleH=256 pages=1 packed=0
			Match match = Regex.Match(line, @"lineHeight=(?<height>\d+) ");
			Debug.Assert(match.Success, "PKBmpFontConfig.ParseCommonArguments: Cannot get correct arguments.");

			this.CommonHeight = int.Parse(match.Groups["height"].Value);

			match = Regex.Match(line, @"pages=(?<pages>\d+) ");
			Debug.Assert(match.Success, "PKBmpFontConfig.ParseCommonArguments: Cannot get correct arguments.");

			int pages = int.Parse(match.Groups["pages"].Value);
			Debug.Assert(pages == 1, "Only supports 1 page.");
		}

		private void ParseImageFileName(string line, string fntFile)
		{
			// For example:
			// page id=0 file="bitmapFontTest.png"
			// page id=0 file="MSYaHei.png"
			Match match = Regex.Match(line, "id=0 file=\"(?<file>.+\\.png)\"");
			Debug.Assert(match.Success, "PKBmpFontConfig.ParseImageFileName: Cannot get correct arguments.");

			this.Name = (Path.GetDirectoryName(fntFile) + "\\" + match.Groups["file"].Value).ToLower();
		}

		private static PKBmpFontDef ParseCharDef(string line)
		{
			// For example:
			// char id=32   x=0     y=0     width=0     height=0     xoffset=0     yoffset=26    xadvance=7     page=0  chnl=0 
			// char id=32   x=254   y=0     width=1     height=1     xoffset=0     yoffset=26    xadvance=8     page=0  chnl=15
			Match match = Regex.Match(line, @"id=(?<id>\d+)\s+x=(?<x>\d+)\s+y=(?<y>\d+)\s+width=(?<width>\d+)\s+height=(?<height>\d+)\s+xoffset=(?<xoffset>-?\d+)\s+yoffset=(?<yoffset>\d+)\s+xadvance=(?<xadvance>\d+) ");
			Debug.Assert(match.Success, "PKBmpFontConfig.ParseCharDef: Cannot get correct arguments.");

			PKBmpFontDef fontDef = new PKBmpFontDef();
			fontDef.CharId = ushort.Parse(match.Groups["id"].Value);
			int x = int.Parse(match.Groups["x"].Value);
			int y = int.Parse(match.Groups["y"].Value);
			int width = int.Parse(match.Groups["width"].Value);
			int height = int.Parse(match.Groups["height"].Value);
			fontDef.Rect = new Rectangle(x, y, width, height);
			fontDef.XOffset = int.Parse(match.Groups["xoffset"].Value);
			fontDef.YOffset = int.Parse(match.Groups["yoffset"].Value);
			fontDef.XAdvance = int.Parse(match.Groups["xadvance"].Value);

			return fontDef;
		}

		private void ParseKerningEntry(string line)
		{
			// For example:
			// kerning first=40  second=106  amount=2
			// kerning first=123  second=106  amount=2
			Match match = Regex.Match(line, @"first=(?<first>\d+)\s+second=(?<second>\d+)\s+amount=(?<amount>-?\d+)");
			Debug.Assert(match.Success, "PKBmpFontConfig.ParseKerningEntry: Cannot get correct arguments.");

			ushort first = ushort.Parse(match.Groups["first"].Value);
			ushort second = ushort.Parse(match.Groups["second"].Value);
			int amount = int.Parse(match.Groups["amount"].Value);
			uint key = (uint)((first << 16) | (second & 0xffff));

			this.kerningDict.Add(key, amount);
		}
		#endregion
	}
}
